package com.tencent.compose.sample.mainpage.material3

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview

@Preview()
@Composable
internal fun TextFieldDemo() {
    var text by remember { mutableStateOf("") }
    val isError by remember {
        derivedStateOf {
            text.length < 3 && text.isNotEmpty()
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center
    ) {
        TextField(
            value = text,
            onValueChange = { newValue ->
                text = newValue
            },
            label = { Text("请输入至少3个字符") },
            placeholder = { Text("在此处输入内容") },
            isError = isError,
            supportingText = {
                if (isError) {
                    Text("输入内容长度至少为3个字符")
                }
            },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.padding(vertical = 8.dp))
        Button(
            onClick = {
                // 这里可以添加点击按钮后的逻辑，比如提交输入的内容
                println("输入的内容是：$text")
            },
            enabled = text.length >= 3
        ) {
            Text("提交")
        }
    }
}
